package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author huangqicai
 * @since 2022-10-21
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private EduVideoMapper videoMapper;

    @Autowired
    private VodClient vodClient;

    /*删除小节*/
    @Override
    public boolean delete(String id) {
        /*根据小节id得到视频id,根据视频id去阿里云里面删除*/
        EduVideo eduVideo = baseMapper.selectById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)){
            R res = vodClient.removeAliVideo(videoSourceId);
            if(res.getCode()==20001){
                throw new GuliException(20001,"删除视频失败，熔断器。。。");
            }
        }
        int res = videoMapper.deleteById(id);
        if(res>0){
            return true;
        }
        return false;
    }

    /*根据课程id删除课程小节*/
    @Override
    public boolean deleteVideo(String courseId) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        int delete = baseMapper.delete(wrapper);
        if(delete>0){
            return true;
        }
        return false;
    }

    /*根据课程id查询与该课程有关的视频ids*/
    @Override
    public ArrayList<String> selectVideoIds(String courseId) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        /*表示查询的时候只是查询这一列*/
        wrapper.select("video_source_id");
        List<EduVideo> eduVideos = baseMapper.selectList(wrapper);
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < eduVideos.size(); i++) {
            EduVideo eduVideo = eduVideos.get(i);
            String videoSourceId = eduVideo.getVideoSourceId();
            if(!StringUtils.isEmpty(videoSourceId)){
                arrayList.add(videoSourceId);
            }
        }
        return arrayList;
    }

    /*根据小节的id查询小节里面的视频SourceId*/
    @Override
    public R getVideo(String videoId) {
        System.out.println("获取到的:"+videoId);
        /*1.根据小节id查询视频id*/
        EduVideo eduVideo = baseMapper.selectById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();
        R r = vodClient.getPlayAuth(videoSourceId);
        return r;
    }

}
